package org.jeecg.modules.edu.base.controller;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONException;
import com.xiaoleilu.hutool.json.JSONObject;
import com.zhaodui.fxy.JSONHelper;
import com.zhaodui.wxmsg.WxMssVo;
import com.zhaodui.wxmsg.accessToken;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.base.entity.WxConfigEntity;
import org.jeecg.modules.base.service.impl.WxConfigEntityServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
@Component
public class CommonUtil {
     @Autowired
    private WxConfigEntityServiceImpl wxConfigEntityService;
     @Autowired
     private RedisUtil redisUtil;
    public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    //获取小程序token
    public  String getToken(String appCode) {
         String rediskey = appCode.split("-")[0];//按照-拆分
        if(redisUtil.hasKey(rediskey)){
            return redisUtil.get(rediskey).toString();
        }
        WxConfigEntity wxConfigEntity = wxConfigEntityService.getUserByappcode(appCode);

        String access_token ="";
        String appid = wxConfigEntity.getAppId();
        String appsecret =  wxConfigEntity.getAppSecret();
        accessToken token = null;
        String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        // 发起GET请求获取凭证
        net.sf.json.JSONObject jsonObject = JSONHelper.toJSONObject(HttpUtil.get(requestUrl));

        if (null != jsonObject) {
            try {
                token = new accessToken();
                access_token  = jsonObject.getString("access_token");
                                token.setExpiresIn(jsonObject.getString("expires_in"));

                redisUtil.set(rediskey ,access_token, Long.parseLong(token.getExpiresIn()));

            } catch (JSONException e) {
                access_token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.get("errcode"), jsonObject.get("errmsg"));
            }
        }
        return access_token;
    }
    //发送模板消息
    public static String sendTemplateMessage(WxMssVo wxMssVo) {
        String info = "";
        try {
            //创建连接
            URL url = new URL(wxMssVo.getRequest_url());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Type", "utf-8");
            connection.connect();
            //POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            JSONObject obj = new JSONObject();

            obj.put("access_token", wxMssVo.getAccess_token());
            obj.put("touser", wxMssVo.getTouser());
            obj.put("template_id", wxMssVo.getTemplate_id());
            obj.put("form_id", wxMssVo.getForm_id());
            obj.put("page", wxMssVo.getPage());

            JSONObject jsonObject = new JSONObject();

            for (int i = 0; i < wxMssVo.getParams().size(); i++) {
                JSONObject dataInfo = new JSONObject();
                dataInfo.put("value", wxMssVo.getParams().get(i).getValue());
                dataInfo.put("color", wxMssVo.getParams().get(i).getColor());
                jsonObject.put("keyword" + (i + 1), dataInfo);
            }

            obj.put("data", jsonObject);
            out.write(obj.toString().getBytes());
            out.flush();
            out.close();

            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            info = sb.toString();
            System.out.println(sb);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

}
